﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using Zove.Runtime.Core;
using Zove.Runtime.Core.Zoom;

namespace Zove.Runtime.Queries.Editor {
    public partial class QueryEditor : Form {
        private BackgroundWorker backgroundWorker1;
        protected string fileName = string.Empty;

        private Query query;

        private Dictionary<string, QueryResult> results;

        public QueryEditor() {
            InitializeComponent();

            Load += QueryEditor_Load;
        }

        public QueryEditor(string fileName)
            : this() {
            this.fileName = fileName;
        }

        public string Source {
            get { return tbQuery.Text; }
            set { tbQuery.Text = value; }
        }

        public void QueryEditor_Load(object sender, EventArgs e) {
            //backgroundWorker1 = new BackgroundWorker();
            //backgroundWorker1.DoWork +=
            //    new DoWorkEventHandler
            //        (backgroundWorker1_DoWork);
            //backgroundWorker1.RunWorkerCompleted +=
            //    new RunWorkerCompletedEventHandler(
            //        backgroundWorker1_RunWorkerCompleted);
            //backgroundWorker1.ProgressChanged +=
            //    new ProgressChangedEventHandler(
            //        backgroundWorker1_ProgressChanged);

            string layout = ConfigurationManager.AppSettings[
                "layout"];
            if (layout == "Horizonal") {
                splitContainer1.Orientation = Orientation.Horizontal;
            } else {
                splitContainer1.Orientation = Orientation.Vertical;
            }

            string font = ConfigurationManager.AppSettings["font"];
            string size = ConfigurationManager.AppSettings["font size"];
            tbQuery.Font = new Font(font, Convert.ToInt32(size));

            gvResult.ContextMenuStrip = new ContextMenuStrip();
            gvResult.ContextMenuStrip.RenderMode = ToolStripRenderMode.System;
            gvResult.ContextMenuStrip.Items.Add(
                "&Show Trace", null,
                ShowTrace);
            gvResult.ContextMenuStrip.Items.Add(
                "&Copy", null,
                Copy);
            gvResult.ContextMenuStrip.Items.Add(
                "Copy &Expression Only", null,
                CopySolution);
        }

        public void ShowTrace(object sender, EventArgs args) {
            DataGridViewRow row = gvResult.Rows[
                gvResult.SelectedCells[0].RowIndex];
            DataGridViewCell cell = row.Cells[0];

            RuntimeFactor rf = query.Model.GetFactorByName(cell.Value.ToString());
            if (rf != null) {
                //TraceView w = new TraceView(rf);

                //w.MdiParent = this.MdiParent;
                //w.Show();
                //w.Show(rf);
            }
        }

        public void Copy(object sender, EventArgs args) {
            if (gvResult.SelectedCells.Count == 0) {
                return;
            }

            Clipboard.SetText(gvResult.SelectedCells[0].Value.ToString());
        }

        public void CopySolution(object sender, EventArgs args) {
        }

        private void newToolStripMenuItem_Click(object sender, EventArgs e) {
            NewFile();
        }

        public void NewFile() {
            UpdateFile(string.Empty);
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e) {
            OpenFile();
        }

        public void UpdateFile(string fileName) {
            if (string.IsNullOrEmpty(fileName)) {
                this.fileName = string.Empty;
                tbQuery.Text = string.Empty;
                Text = "Zove Query Editor - [Untitled]";

                return;
            }

            this.fileName = fileName;
            tbQuery.Text = File.ReadAllText(fileName);
            Text = "Zove Query Editor - [" + fileName + "]";
        }

        public void OpenFile() {
            var d = new OpenFileDialog();

            if (d.ShowDialog() == DialogResult.OK) {
                UpdateFile(d.FileName);
            }
        }

        public void Save() {
            if (string.IsNullOrEmpty(fileName)) {
                SaveAs();
            } else {
                File.WriteAllText(
                    fileName, tbQuery.Text);
            }
        }

        public void SaveAs() {
            var d = new SaveFileDialog();

            if (d.ShowDialog() == DialogResult.OK) {
                fileName = d.FileName;
                tbQuery.SaveFile(d.FileName);
                UpdateFile(d.FileName);
            }
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e) {
            Save();
        }

        private void saveAsToolStripMenuItem_Click(object sender, EventArgs e) {
            SaveAs();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e) {
            Close();
        }

        private void cmdNew_Click(object sender, EventArgs e) {
            NewFile();
        }

        private void cmdOpen_Click(object sender, EventArgs e) {
            OpenFile();
        }

        private void cmdSave_Click(object sender, EventArgs e) {
            Save();
        }

        private void cmdRun_Click(object sender, EventArgs e) {
            Run();
        }

        public void Run() {
            string queryText = string.Empty;

            if (string.IsNullOrEmpty(
                tbQuery.ActiveTextAreaControl.TextArea.SelectionManager.SelectedText)) {
                queryText = tbQuery.Document.TextContent;
            } else {
                queryText = tbQuery.ActiveTextAreaControl.TextArea.SelectionManager.SelectedText;
            }

            if (!queryText.EndsWith(";")) {
                queryText = queryText + ";";
            }

            var queryManager = new QueryManager(new ZoomLanguageNature());
            query = queryManager.CreateQuery(queryText);
            results = query.Run();

            gvResult.Rows.Clear();
            foreach (QueryResult result in results.Values) {
                gvResult.Rows.Add(new[]
                                      {
                                          result.Item, result.Value, result.Unit, result.Expression
                                      });
            }
        }

        private void horizoanlToolStripMenuItem_Click(object sender, EventArgs e) {
            splitContainer1.Orientation = Orientation.Horizontal;
        }

        private void verticalToolStripMenuItem_Click(object sender, EventArgs e) {
            splitContainer1.Orientation = Orientation.Vertical;
        }

        private void optionsToolStripMenuItem_Click(object sender, EventArgs e) {
            var view = new OptionsView();

            if (view.ShowDialog() == DialogResult.OK) {
            }
        }
    }
}